package org.longteng.core.utils;

import cn.hutool.core.io.IoUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.util.Base64;

/**
 * 图片处理工具类
 * 如：图片文件转成前端Base64，前端图片Base64转成byte[]等
 *
 */
@Slf4j
public class ImageUtil {

    /**
     * 图片转成base64
     * @param imgFileName
     * @return
     */
    public static String imgToBase64(String imgFileName) {
        String base64Str = null;
        String substring = imgFileName.substring(imgFileName.lastIndexOf('.')+1);

            //"E:/static-resource/ihospital/doctorSign/doctor_sign_img-1.png"
            File imgFile =  new File(imgFileName);
        try (FileInputStream fileInputStream = new FileInputStream(imgFile);){
            byte[] data = IoUtil.readBytes(fileInputStream, true);
            base64Str = Base64.getEncoder().encodeToString(data); // Base64.encodeBase64String(data);
            // base64Str.replaceAll("\n", "").replaceAll("\r", "");  // getEncoder,getUrlEncoder 和 getMimeEncoder地有换行
        } catch (IOException e) {
            log.error("图片转成base64错误.",e);
        }
        return "data:image/" + substring + ";base64,"+ base64Str;
    }

    /**
     * 图片转成base64
     * @param imgResourceName  类资源包中载入，不用\开头
     * @return
     */
    public static String imgResourceToBase64(String imgResourceName) {
        String base64Str = null;
        String substring = imgResourceName.substring(imgResourceName.lastIndexOf('.')+1);
        try (InputStream fileInputStream = ImageUtil.class.getClassLoader().getResourceAsStream(imgResourceName)){
            byte[] data = IoUtil.readBytes(fileInputStream, true);
            base64Str = Base64.getEncoder().encodeToString(data); // Base64.encodeBase64String(data);
            // base64Str.replaceAll("\n", "").replaceAll("\r", "");  // getEncoder,getUrlEncoder 和 getMimeEncoder地有换行
        } catch (IOException e) {
            log.error("图片转成base64错误.",e);
        }
        return "data:image/" + substring + ";base64,"+ base64Str;
    }

    /**
     * 将图形文件转换为 MultipartFile类型
     * @param imgFile
     * @return ImgMultipartFile
     */
    public static ImgMultipartFile fileToMultipart(File imgFile) {
        if(imgFile == null) {
            return  null;
        }
        String baseStrs = "data:image/"+imgFile.getName();
        byte[]  data = null;
        try (FileInputStream fileInputStream = new FileInputStream(imgFile);){
            data = IoUtil.readBytes(fileInputStream, true);
        } catch (IOException e) {
            log.error("图片读取错误.",e);
        }
        return new ImageUtil.ImgMultipartFile(data, baseStrs);
    }

    /**
     * 将base64转换为 MultipartFile类型
     * @param imgBase64
     * @return ImgMultipartFile
     */
    public static ImgMultipartFile base64ToMultipart(String imgBase64) {
        String[] baseStrs = imgBase64.split(",");
        String imgContentBase64 = baseStrs!=null && baseStrs.length >1 ? baseStrs[1] : imgBase64;
        // /lib/tool.jar和/lib/rt.jar已经从JDK9中删除
        // 如果你不是JDK 9及以上的版本 可以使用
        byte[]  b = Base64.getDecoder().decode(imgContentBase64);
        for(int i = 0; i < b.length; ++i) {
            if (b[i] < 0) {
                b[i] += 256;
            }
        } // end for

        return new ImageUtil.ImgMultipartFile(b, baseStrs[0]);
    }

    /**
     * 图片MultipartFile类型
     */
    public static class ImgMultipartFile {
        private final byte[] imgContent;
        private final String header;

        /**构建文件类型*/
        public ImgMultipartFile(byte[] imgContent, String header) {
            this.imgContent = imgContent;
            this.header = header.split(";")[0];
        }
        /**返回文件名"png"*/
        public String getFileType() {
            return header.split("/")[1];
        }
        /**返回文件名*/
        public String getName() {
            return System.currentTimeMillis() + Math.random() + "." + header.split("/")[1];
        }
        /**返回文件名*/
        public String getOriginalFilename() {
            return System.currentTimeMillis() + (int)Math.random() * 10000 + "." + header.split("/")[1];
        }
        /**返回图片文件大小*/
        public long getSize() {
            return imgContent.length;
        }
        /**返回图片文件内容*/
        public byte[] getBytes() throws IOException {
            return imgContent;
        }
        /**返回文件流*/
        public InputStream getInputStream() throws IOException {
            return new ByteArrayInputStream(imgContent);
        }
        /**返将图片文件另存到目标文件*/
        public void transferTo(File dest) throws IOException, IllegalStateException {
            new FileOutputStream(dest).write(imgContent);
        }

        /**返回图片头”image/png“*/
        public String getContentType() {
            return header.split(":")[1];
        }
        /**内容是否空*/
        public boolean isEmpty() {
            return imgContent == null || imgContent.length == 0;
        }


    }

}
